package com.zghhost.codedemo.net.socket;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.InputStreamReader;
import java.io.OutputStreamWriter;
import java.net.Socket;

/**
 * @author guohua.zhang@zhaopin.com.cn
 * @Date 2019/3/29 15:16
 */
public class MySocketHandler extends Thread{
    private Socket socket;

    public MySocketHandler(Socket socket){
        this.socket = socket;
    }

    @Override
    public void run() {
        try{
            System.out.println("客户端连接成功："+socket.getInetAddress()+":"+socket.getPort());
            System.out.println("会话创建成功，当前处理人："+Thread.currentThread().getId());
            BufferedReader br = new BufferedReader(new InputStreamReader(socket.getInputStream()));
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream()));
            String line=null;
            while((line = br.readLine()) != null){
                System.out.println(line);
                if(line.endsWith("?") || line.endsWith("？")){
                    bw.write(line.replaceAll("[\\?|？]",""));
                }else{
                    bw.write(line);
                }
                bw.write("\n");
                bw.flush();
            }
            System.out.println("本次会话结束");
        }catch (Exception e){
            System.out.println("客户端发生异常");
            e.printStackTrace();
        }
    }
}
